package com.study.netty.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/28 14:17
 */
public class GroupChatServer {

    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞
            listenChannel.configureBlocking(false);
            //listen注册到 selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (Exception e) {

        }
    }

    public void listen() {
        try {
            while (true) {
                int count = selector.select(2000);
                if (count > 0) {
                    //遍历得到的key
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();

                        //监听到accept
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            //将该ac到selector
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + " 上线");
                        }
                        if (key.isReadable()) {//通道可读
                            //处理读
                        }

                        //当前key删除，放置重复处理

                    }

                } else {
                    System.out.println("等待中");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public void readData(SelectionKey key) throws IOException {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);

            if (count > 0) {
                //把缓冲区的数据转成字符串
                String msg = new String(buffer.array());
                System.out.println("from 客户端 " + msg);
                //向其他客户端转发消息
                sendInfoToOtherClients(msg,channel);
            }

        } catch (IOException e) {
            System.out.println(channel.getRemoteAddress() + " 下线了……");
            //取消注册
            key.cancel();
            //关闭通道
            channel.close();
        }
    }

    //转发消息
    private void sendInfoToOtherClients(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中……");

        //遍历所有注册到select的socketChannel，并排除自己
        for (SelectionKey key : selector.keys()) {
            //通过key 取出对应的 socketchannel
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                //转型
                SocketChannel dest = (SocketChannel) targetChannel;
                //将msg存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                dest.write(buffer);
            }
        }
    }
}
